﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.ProductionSystemDto.ProductionMaterialDto;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace ThridGroup.ERP.ProductionSystem
{
    /// <summary>
    /// 生产领料服务接口实现层   ---tsh    
    /// </summary>
    public class ProductionMaterialServices : ApplicationService, IProductionMaterialServices
    {
        private readonly IRepository<ProductionMaterial, int> _productionMaterialRepository;

        public ProductionMaterialServices(IRepository<ProductionMaterial, int> productionMaterialRepository)
        {
            _productionMaterialRepository = productionMaterialRepository;
        }

        /// <summary>
        /// 获取生产领料列表
        /// </summary>
        /// <param name="input">查询参数</param>
        /// <returns>生产领料列表</returns>
        public async Task<object> GetListAsync(GetProductionMaterialDto input)
        {
            try
            {
                var query = await _productionMaterialRepository.GetQueryableAsync();

                // 应用筛选条件
                if (!string.IsNullOrEmpty(input.IssuanceOrderCode))
                {
                    query = query.Where(x => x.IssuanceOrderCode.Contains(input.IssuanceOrderCode));
                }

                if (!string.IsNullOrEmpty(input.IssuanceOrderName))
                {
                    query = query.Where(x => x.IssuanceOrderName.Contains(input.IssuanceOrderName));
                }

                if (!string.IsNullOrEmpty(input.ProductionWorkOrder))
                {
                    query = query.Where(x => x.ProductionWorkOrder.Contains(input.ProductionWorkOrder));
                }

                if (!string.IsNullOrEmpty(input.IssuanceWarehouse))
                {
                    query = query.Where(x => x.IssuanceWarehouse.Contains(input.IssuanceWarehouse));
                }

                if (!string.IsNullOrEmpty(input.CustomerName))
                {
                    query = query.Where(x => x.CustomerName.Contains(input.CustomerName));
                }

                if (input.StartDate.HasValue)
                {
                    query = query.Where(x => x.IssuanceDate >= input.StartDate.Value);
                }

                if (input.EndDate.HasValue)
                {
                    query = query.Where(x => x.IssuanceDate <= input.EndDate.Value);
                }

                // 获取总数
                var totalCount = query.Count();

                // 分页
                var items = query
                    .OrderByDescending(x => x.RecordCreateTime)
                    .Skip((input.page - 1) * input.limit)
                    .Take(input.limit)
                    .ToList();

                return new
                {
                    code = 0,
                    msg = "获取成功",
                    count = totalCount,
                    data = items
                };
            }
            catch (Exception ex)
            {
                return new
                {
                    code = 1,
                    msg = "获取失败：" + ex.Message,
                    count = 0,
                    data = new List<object>()
                };
            }
        }

        /// <summary>
        /// 根据ID获取生产领料详情
        /// </summary>
        /// <param name="id">生产领料ID</param>
        /// <returns>生产领料详情</returns>
        public async Task<object> GetAsync(int id)
        {
            try
            {
                var entity = await _productionMaterialRepository.GetAsync(id);
                if (entity == null)
                {
                    return new { code = 1, msg = "数据不存在" };
                }

                return new
                {
                    code = 0,
                    msg = "获取成功",
                    data = entity
                };
            }
            catch (Exception ex)
            {
                return new
                {
                    code = 1,
                    msg = "获取失败：" + ex.Message
                };
            }
        }

        /// <summary>
        /// 创建生产领料
        /// </summary>
        /// <param name="input">创建参数</param>
        /// <returns>创建结果</returns>
        public async Task<object> CreateAsync(CreateProductionMaterialDto input)
        {
            try
            {
                // 检查领料单编号是否重复
                var existingEntity = await _productionMaterialRepository.FirstOrDefaultAsync(x => x.IssuanceOrderCode == input.IssuanceOrderCode);
                if (existingEntity != null)
                {
                    return new { code = 1, msg = "领料单编号已存在" };
                }

                var entity = ObjectMapper.Map<CreateProductionMaterialDto, ProductionMaterial>(input);
                entity.RecordCreateTime = DateTime.Now;
                entity.RecordUpdateTime = DateTime.Now;

                await _productionMaterialRepository.InsertAsync(entity);

                return new
                {
                    code = 0,
                    msg = "创建成功",
                    data = entity
                };
            }
            catch (Exception ex)
            {
                return new
                {
                    code = 1,
                    msg = "创建失败：" + ex.Message
                };
            }
        }

        /// <summary>
        /// 更新生产领料
        /// </summary>
        /// <param name="id">生产领料ID</param>
        /// <param name="input">更新参数</param>
        /// <returns>更新结果</returns>
        public async Task<object> UpdateAsync(int id, UpdateProductionMaterialDto input)
        {
            try
            {
                var entity = await _productionMaterialRepository.GetAsync(id);
                if (entity == null)
                {
                    return new { code = 1, msg = "数据不存在" };
                }

                // 检查领料单编号是否重复（排除当前记录）
                var existingEntity = await _productionMaterialRepository.FirstOrDefaultAsync(x => x.IssuanceOrderCode == input.IssuanceOrderCode && x.Id != id);
                if (existingEntity != null)
                {
                    return new { code = 1, msg = "领料单编号已存在" };
                }

                ObjectMapper.Map(input, entity);
                entity.RecordUpdateTime = DateTime.Now;

                await _productionMaterialRepository.UpdateAsync(entity);

                return new
                {
                    code = 0,
                    msg = "更新成功",
                    data = entity
                };
            }
            catch (Exception ex)
            {
                return new
                {
                    code = 1,
                    msg = "更新失败：" + ex.Message
                };
            }
        }

        /// <summary>
        /// 删除生产领料
        /// </summary>
        /// <param name="id">生产领料ID</param>
        /// <returns>删除结果</returns>
        public async Task<object> DeleteAsync(int id)
        {
            try
            {
                var entity = await _productionMaterialRepository.GetAsync(id);
                if (entity == null)
                {
                    return new { code = 1, msg = "数据不存在" };
                }

                await _productionMaterialRepository.DeleteAsync(id);

                return new
                {
                    code = 0,
                    msg = "删除成功"
                };
            }
            catch (Exception ex)
            {
                return new
                {
                    code = 1,
                    msg = "删除失败：" + ex.Message
                };
            }
        }

        /// <summary>
        /// 生成领料单编号
        /// </summary>
        /// <returns>领料单编号</returns>
        public async Task<string> GenerateIssuanceOrderCodeAsync()
        {
            try
            {
                var today = DateTime.Now.ToString("yyyyMMdd");
                var prefix = "LLD" + today; // 领料单 + 日期

                var query = await _productionMaterialRepository.GetQueryableAsync();
                var maxCode = query
                    .Where(x => x.IssuanceOrderCode.StartsWith(prefix))
                    .Select(x => x.IssuanceOrderCode)
                    .ToList()
                    .Select(x => x.Substring(prefix.Length))
                    .Where(x => int.TryParse(x, out _))
                    .Select(x => int.Parse(x))
                    .DefaultIfEmpty(0)
                    .Max();

                var newNumber = maxCode + 1;
                return prefix + newNumber.ToString("D3"); // 3位数字，不足前面补0
            }
            catch
            {
                return "LLD" + DateTime.Now.ToString("yyyyMMdd") + "001";
            }
        }
    }
}
